using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;

namespace PhotoBlenderLib {
	class PhotoStorage {

		private static string constring = string.Empty;
		private static SqlConnection sqlCon;
		private static SqlCommand sqlCmdGet;
		private static SqlCommand sqlCmdSet;

		static PhotoStorage() {
			constring = ConfigurationManager.AppSettings["ConnectionString"];

			// set up connection
			sqlCon = new SqlConnection(constring);

			// setup store command
			sqlCmdSet = new SqlCommand("pb_Pixel_Store", sqlCon);
			sqlCmdSet.CommandType = CommandType.StoredProcedure;

			sqlCmdSet.Parameters.Add("@PhotoSet", SqlDbType.Int);
			sqlCmdSet.Parameters.Add("@X", SqlDbType.SmallInt);
			sqlCmdSet.Parameters.Add("@Y", SqlDbType.SmallInt);
			sqlCmdSet.Parameters.Add("@R", SqlDbType.TinyInt);
			sqlCmdSet.Parameters.Add("@G", SqlDbType.TinyInt);
			sqlCmdSet.Parameters.Add("@B", SqlDbType.TinyInt);

			sqlCmdSet.Parameters["@PhotoSet"].Value = 1;


			// setup get command
			sqlCmdGet = new SqlCommand("pb_Pixel_GetAverage", sqlCon);
			sqlCmdGet.CommandType = CommandType.StoredProcedure;

			sqlCmdGet.Parameters.Add("@PhotoSet", SqlDbType.Int);
			sqlCmdGet.Parameters.Add("@X", SqlDbType.SmallInt);
			sqlCmdGet.Parameters.Add("@Y", SqlDbType.SmallInt);
			sqlCmdGet.Parameters.Add("@R", SqlDbType.TinyInt);
			sqlCmdGet.Parameters.Add("@G", SqlDbType.TinyInt);
			sqlCmdGet.Parameters.Add("@B", SqlDbType.TinyInt);

			sqlCmdGet.Parameters["@PhotoSet"].Value = 1;

			sqlCon.Open();

			sqlCmdSet.Prepare();
			sqlCmdGet.Prepare();
		}

		public static void StorePixel(int PhotoSet, int x, int y, Color color) {
			
			int r = color.R;
			int g = color.G;
			int b = color.B;
			
			sqlCmdSet.Parameters["@X"].Value = x;
			sqlCmdSet.Parameters["@Y"].Value = y;
			sqlCmdSet.Parameters["@R"].Value = r;
			sqlCmdSet.Parameters["@G"].Value = g;
			sqlCmdSet.Parameters["@B"].Value = b;

			//sqlCon.Open();
			sqlCmdSet.ExecuteNonQuery();
			//sqlCon.Close();
			
		}

		public static Color GetPixelAverage(int PhotoSet, int x, int y) {
			
			Color color;

			sqlCmdGet.Parameters["@X"].Value = x;
			sqlCmdGet.Parameters["@Y"].Value = y;
			sqlCmdGet.Parameters["@R"].Direction = ParameterDirection.Output;
			sqlCmdGet.Parameters["@G"].Direction = ParameterDirection.Output;
			sqlCmdGet.Parameters["@B"].Direction = ParameterDirection.Output;

			sqlCmdGet.ExecuteNonQuery();

			byte r = (byte)sqlCmdGet.Parameters["@R"].Value;
			byte g = (byte)sqlCmdGet.Parameters["@G"].Value;
			byte b = (byte)sqlCmdGet.Parameters["@B"].Value;

			color = Color.FromArgb(r, g, b);

			return color;
		}

	}
}
